package com.credithc.signature.common.service.lanmao;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author zhanghanqiu181212@credithc.com
 * @Date 2019/10/17 17:38
 */
@Service
@Slf4j
public class LanmaoFileService {

    @Value("${cat.sdk.customerNo:911101135769049507A}")
    private String customerNo;

    @Value("${cat.sdk.method.fileUploadMethod:/sign/contract/upload}")
    private String fileUploadMethod;

    @Value("${cat.sdk.method.downloadFileMethod:/sign/contract/download}")
    private String downloadFileMethod;

    @Autowired
    private LanmaoSdkClient lanmaoSdkClient;

    /**
     * 根据文件路径读取文件
     * @param path 文件路径
     * @return
     */
    protected static byte[] getFileByte(String path) {
        File file = new File(path);
        InputStream in = null;
        byte[] bytes = null;//文件流
        try {
            in = new FileInputStream(file);
            // 取得文件大小
            long length = file.length();
            // 根据大小创建字节数组
            bytes = new byte[(int) length];
            // 读取文件内容到字节数组**
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length
                    && (numRead = in.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += numRead;
            }
            // 读取完毕的校验
            if (offset < bytes.length) {
                System.out.println("不能完全读取的文件："+ file.getName());
            }
            if(null != in){
                in.close();
            }
        } catch ( FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("读取流异常");
        } catch (IOException e1) {
            e1.printStackTrace();
            System.out.println("读取流异常");
        }
        return bytes;
    }

    /**
     * md5
     * @param data
     * @return
     */
    public static String md5(byte[] data) {
        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
        byte[] btInput = data;
        // 获得MD5摘要算法的 MessageDigest 对象
        MessageDigest mdInst;
        try {
            mdInst = MessageDigest.getInstance("MD5");
        }
        catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        // 使用指定的字节更新摘要
        mdInst.update(btInput);
        // 获得密文
        byte[] md = mdInst.digest();
        // 把密文转换成十六进制的字符串形式
        int j = md.length;
        char str[] = new char[j * 2];
        int k = 0;
        for (int i = 0; i < j; i++) {
            byte byte0 = md[i];
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }
        return new String(str);
    }

    /**
     *  合同上传
     */
    public String contractUpload(String userId,String filePath,String fname,String title) {

        try {
            //上传合同
            byte[] fileBytes = getFileByte(filePath);
            JSONObject body = new JSONObject();
            body.put("userId", userId);
            body.put("fmd5", md5(fileBytes));
            body.put("ftype", "pdf");
            body.put("fname", fname);
            body.put("fdata", Base64.encodeBase64String(fileBytes));
            body.put("title", title);
            body.put("expireTime", Long.toString(System.currentTimeMillis() / 1000 + (3600 * 24 * 7)));
            JSONObject postData = new JSONObject();
            JSONObject head = new JSONObject();
            head.put("customerNo", customerNo);
            postData.put("head", head);
            postData.put("body", body);

            JSONObject response = lanmaoSdkClient.post(fileUploadMethod, postData);
            log.info("上传文件成功--返回值为{}",response.toJSONString());
           // System.err.println(response.toJSONString());
            if (!response.isEmpty() && response.containsKey("body") && response.getJSONObject("body").containsKey("contractId")) {
                return response.getJSONObject("body").getString("contractId");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  将文件下载到指定位置
     */
    public void contactDownload(String contractId,String targetPath) {
       // String signupMethod = "/sign/contract/download";
        try {
            JSONObject body = new JSONObject();
            body.put("contractId", contractId);

            JSONObject postData = new JSONObject();
            JSONObject head = new JSONObject();
            head.put("customerNo", customerNo);
            postData.put("head", head);
            postData.put("body", body);
            JSONObject response = lanmaoSdkClient.post(downloadFileMethod, postData);
            System.err.println(response.getJSONObject("head").toJSONString());
            if (!response.isEmpty() && response.containsKey("body") && response.getJSONObject("body").containsKey("data")) {
                decoderBase64File( response.getJSONObject("body").getString("data"),targetPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 将base64字符解码保存文件
     *
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static void decoderBase64File(String base64Code, String targetPath)
            throws Exception {

        byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }



}
